<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import {
  showToast,
  navigateTo,
  showModal,
  showLoading,
  eventCenter,
  getCurrentInstance,
} from '@tarojs/taro';
import ItemTypeSelectDepartment from './item-type-select-department.vue';
import ItemTypeForm from './item-type-form.vue';
import { ADD_FPR_PRODUCT_REQ } from '/@/api/modules/flow-path/flow-path-product';
import { ItemTypeDto } from '../index';
import { QUERY_FTD_FOR_ADD_FLOW } from '/@/api/modules/flow-path/flow-path-template';
import ApproveProcessList from '../../../../approve/edit/components/approve-process-list/approve-process-list.vue';
import { FIND_ONE, SAVE, DELETE } from '/@/api/modules/flow-path/flow-path-draft';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { QUERY_APP_FLOW_PATH_RECORD_DETAIL } from '/@/api/modules/flow-path/flow-path';
import { QUERY_FPR_PRODUCT_LIST_REQ } from '/@/api/modules/flow-path/flow-path-product';
import { QUERY_FLOW_PATH_TEMPLATE_CONTRACT } from '/@/api/modules/flow-path/flow-path-template-contract';
import { state as resultPageState } from '../../../submit-success/state';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as unknown as {
  templateCodeList?: string;
  /**
   * 审批ID
   */
  id?: string;
};

const formState: {
  organizationId: string;
  organizationName: string;
  addFprProductDtoList: IbFpProductApi.AddProductDto[];
  templateCode: string;
  flowGraphAddFlow?: FlowPathTemplateApi.FlowGraph;
} = reactive({
  organizationId: '',
  organizationName: '',
  addFprProductDtoList: [],
  templateCode: '',
  flowGraphAddFlow: {},
});

const state = reactive<{
  userId?: string;
  templateId?: string;
  /**
   * 审批流程配置图结构体
   */
  flowGraph?: FlowPathTemplateApi.FlowGraph;
  /**
   * 审批流程配置图结构体
   */
  flowGraphAddFlow?: FlowPathTemplateApi.FlowGraph;
  attributes?: FlowPathTemplateApi.AttributeDto[];
  productList?: FlowPathDraftApi.Product[]; //草稿保存的记录
  /**
   * 产品列表
   */
  sourceProductList: IbFpProductApi.Dto[];
}>({
  userId: '',
  templateId: '',
  flowGraph: {},
  flowGraphAddFlow: {},
  attributes: [],
  productList: [],
  sourceProductList: [],
});

const itemTypeFormRef = ref<InstanceType<typeof ItemTypeForm>>();

/**
 * 子组件的state.list赋值给formState
 */
function updateFormState() {
  formState.addFprProductDtoList = [];
  itemTypeFormRef.value?.dynamicFormRef.list.forEach((item: ItemTypeDto) => {
    formState.addFprProductDtoList.push({
      id: item.productId,
      productName: item.productName,
      productSpecName: item.productSpecName,
      quantity: item.quantity,
    });
  });
}

/**
 * true: 表格全部类容已经填写，false：还有表格字段没填写
 */
function checkForm() {
  /**
   * resultList: 填写类容为true，没填写为false
   */
  const resultList: boolean[] = [];
  formState.addFprProductDtoList.forEach((item) => {
    resultList.push(item.productName && item.productName?.length > 0 ? true : false);
    resultList.push(item.productSpecName && item.productSpecName?.length > 0 ? true : false);
    resultList.push(item.quantity && item.quantity > 0 ? true : false);
  });
  return resultList.every((item) => {
    return item;
  });
}

/**
 * 提交审批
 */
function submit() {
  updateFormState();
  if (!formState.organizationName) {
    showToast({ title: '部门不能为空', icon: 'error' });
    return;
  }
  if (!checkForm()) {
    showToast({ title: '物品类型字段不能为空', icon: 'error' });
    return;
  }

  showLoading();
  formState.flowGraphAddFlow = state.flowGraphAddFlow;
  formState.templateCode = params.templateCodeList || '';
  //物品领用
  ADD_FPR_PRODUCT_REQ(formState).then((res) => {
    if (res.comResp?.code === 100) {
      if (params.id) {
        resultPageState.from = 'list';
      }
      navigateTo({
        url: '/pages/police-security/submit-success/index',
      });
    }
  });
}

function deptChange(deptId: string, deptName: string) {
  formState.organizationId = deptId;
  formState.organizationName = deptName;
}

onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //清理数据，当成功页面返回的时候，显示初始状态
    formState.organizationId = '';
    formState.organizationName = '';
    formState.addFprProductDtoList = [];
  });
  //查询流程
  queryContractList();
});

/**
 * 查询审批模版详情
 * @param code 审批模版code
 */
function queryDetail(code: string) {
  showLoading();
  QUERY_FTD_FOR_ADD_FLOW({ code }).then((res) => {
    state.flowGraph = res.flowpathTemplateDto?.flowGraph;
    state.templateId = res.flowpathTemplateDto?.id;
    state.flowGraphAddFlow = res.flowpathTemplateDto?.flowGraphAddFlow;
    if (params.id) {
      queryApprovedDetail(params.id);
    } else {
      queryDraft(code);
    }
  });
}

function saveDraftByRequest() {
  showLoading();
  SAVE({
    userId: state.userId,
    flowpathRecordDto: {
      templateId: state.templateId,
      templateCode: params.templateCodeList,
      attributes: state.attributes,
    },
    flowGraphAddFlow: state.flowGraphAddFlow,
    deptName: formState.organizationName,
    desc: formState.organizationId,
    productList: itemTypeFormRef.value?.dynamicFormRef.list.map((item: ItemTypeDto) => {
      return {
        productId: item.productId,
        productName: item.productName,
        productSpecName: item.productSpecName,
        quantity: item.quantity,
      };
    }),
  }).then((res) => {
    if (res.comResp?.code === 100) {
      showModal({
        title: '保存草稿成功',
        showCancel: false,
        content: '下次进入申请页面可继续填写表单内容',
      });
    }
  });
}
function saveDraft() {
  if (state.userId) {
    saveDraftByRequest();
  } else {
    showLoading();
    LOGIN_APP().then((res) => {
      state.userId = res.sysUserDto.id;
      saveDraftByRequest();
    });
  }
}

function queryDraft(code: string) {
  showLoading();
  LOGIN_APP().then((res) => {
    state.userId = res.sysUserDto.id;

    FIND_ONE({ templateCode: code, userId: state.userId }).then((res) => {
      if (res.flowpathRecordDto) {
        showModal({
          title: '继续填写',
          content: '你有未提交的内容，是否载入草稿继续填写？',
          success: function (result) {
            if (result.confirm) {
              state.productList = res.productList as FlowPathDraftApi.Product[];
              state.flowGraphAddFlow = res.flowGraphAddFlow;
              formState.organizationId = res.desc || '';
              formState.organizationName = res.deptName || '';
            } else if (result.cancel) {
              deleteDraft(code);
            }
          },
        });
      }
    });
  });
}

function deleteDraft(code: string) {
  DELETE({ templateCode: code, userId: state.userId });
}

/**
 * @function 获取审批详情
 */
function queryApprovedDetail(id: string) {
  showLoading();
  QUERY_APP_FLOW_PATH_RECORD_DETAIL({ id }).then((res) => {
    setDraftAttributes(res.flowpathRecordDto?.attributes);
  });
}

/**
 * 只修改attribute中的值
 */
function setDraftAttributes(attributes?: FlowPathTemplateApi.AttributeDto[]) {
  const deptAttribute = attributes?.find((item) => item.attributeCode === 'dept');
  if (deptAttribute) {
    formState.organizationId = '';
    formState.organizationName = deptAttribute.attributeValue || '';
  }
  const listAttribute = attributes?.find((item) => item.attributeCode === 'list');
  console.log('listAttribute', listAttribute);
  const productList: FlowPathDraftApi.Product[] = [];
  if (listAttribute?.attributeValue) {
    const obj: { data?: string[][]; title?: string[] } = JSON.parse(listAttribute.attributeValue);
    obj.data?.forEach((item) => {
      // "attributeValue": "{\"data\":[[\"中性笔\",\"1\",\"晨光(M&amp;G)Q7 0.5mm 单支装 签字笔\",\"0\",\"\"]],\"title\":[\"物品品类\",\"数量\",\"规格\",\"本年已领\",\"上次使用\"]}",
      const newObj: FlowPathDraftApi.Product = {};
      const product = getProductIdByName(item[0]);
      newObj['productId'] = product?.id || '';
      newObj['productName'] = item[0];
      newObj['productSpecName'] = item[2];
      newObj['quantity'] = parseInt(item[1]);
      productList.push(newObj);
    });
  }
  state.productList = productList;
  console.log('productList', state.productList);
}

function getProductIdByName(productName: string) {
  return state.sourceProductList.find((item) => item.productName === productName);
}

/**
 * 查询合同列表
 *
 */
function queryContractList() {
  showLoading();
  QUERY_FLOW_PATH_TEMPLATE_CONTRACT({ templateCode: params.templateCodeList }).then((res) => {
    if (res.queryFlowpathTemplateContractDto && res.queryFlowpathTemplateContractDto.length > 0) {
      const contractId = res.queryFlowpathTemplateContractDto[0].contractId;
      contractId && getProductList(contractId);
    }
  });
}

/**
 * 获取产品列表
 */
function getProductList(contractId: string) {
  showLoading();
  QUERY_FPR_PRODUCT_LIST_REQ({ contractId, comQuery: { page: 1, pageSize: 1000 } }).then((res) => {
    state.sourceProductList = res.queryFprProductDtoList || [];
    params.templateCodeList && queryDetail(params.templateCodeList);
  });
}
</script>
<template>
  <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
    <view class="item-receive-edit__wrapper">
      <!-- 选择部门 -->
      <nut-form>
        <nut-form-item label="领用部门" required>
          <item-type-select-department
            :dept-id="formState.organizationId"
            :dept-name="formState.organizationName"
            @on-change="deptChange"
          />
        </nut-form-item>
      </nut-form>
      <!-- 选择领用物品 -->
      <item-type-form
        ref="itemTypeFormRef"
        :product-list="state.productList"
        :source-product-list="state.sourceProductList"
      />
      <!-- 流程图 -->
      <approve-process-list
        v-if="state.flowGraphAddFlow && Object.keys(state.flowGraphAddFlow).length > 0"
        :flow-graph-add-flow="state.flowGraphAddFlow"
      />
    </view>
  </scroll-view>
  <view class="item-receive-edit__footer">
    <nut-button class="item-receive-edit__footer-btn" block color="#bbb" @click="saveDraft()">
      存草稿
    </nut-button>
    <nut-button class="item-receive-edit__footer-btn" block type="info" @click="submit()">
      提交
    </nut-button>
  </view>
</template>
<style lang="scss">
.item-receive-edit {
  &__wrapper {
    padding: 20px 20px;
  }
  &__footer {
    padding: 20px 20px;
    background-color: #fff;
    display: flex;
  }
  &__footer-btn {
    flex: 1;
    margin: 0 10px !important;
  }
}
</style>
